<script setup lang="ts">
import { ref, reactive } from "vue";
import { storeToRefs } from "pinia";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { Search, Minus, Plus } from "@element-plus/icons-vue";
import { useEnumStore } from "@/store/enumeration";
import { productLinkConfigAddPost } from "@/api/allProduct";
import { upload, delAttachment } from "@/api/product";
import useInstance from "@/hooks/useInstance";
import { useComListData } from "@/store/list";
import { getProductListAll } from "@/api/product";

import upLoadImgSingle from "@/components/upLoadImgSingle.vue"

const imgUpload1 = ref()

const { listCollect } = storeToRefs(useComListData());
const { getProListAll } = useComListData();
const searchLoading = ref(false)
const { ProductLinkConfigStatusEnum } = storeToRefs(useEnumStore());
defineOptions({
  name: "addProductLink",
});
const emit = defineEmits(["refresh", "searchEdit"]);
const { global } = useInstance();
const newProductListOption = ref<any>();
const dialogBasic = ref({
  title: "新建产品链接配置",
  visible: false,
  width: 700,
  height: 400,
  showFooter: true,
  marginTop: "5vh",
});

const supplyFormRef = ref<FormInstance>();
const addSupply = reactive<any>({
  // channelCode: null, //渠道编码
  // schemeCode: '962628', //权益方案编码
  productCode: null, //产品编码
  productName: null, //产品名称

  productLink: null, //产品链接

  productCategory: null, //产品总分类
  productCategoryCode: null, //产品总分类

  environment: null, //环境
  scenario: null, // 场景
  status: null, // 状态
  remarks: null, // 备注
  attachmentUri: null, // 附件地址
});

const rules = reactive<FormRules>({
  status: [
    {
      required: true,
      trigger: "blur",
      message: "请选择状态",
    },
  ],
  productCategoryCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择产品大类",
    },
  ],
  scenario: [
    {
      required: true,
      trigger: "blur",
      message: "请选择场景",
    },
  ],
  environment: [
    {
      required: true,
      trigger: "blur",
      message: "请选择环境",
    },
  ],
  channelCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择渠道编码",
    },
  ],
  schemeCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择权益方案编码",
    },
  ],
  productCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择产品名称",
    },
  ],
  productCategory: [
    {
      required: true,
      trigger: "blur",
      message: "请选择产品总分类",
    },
  ],
  productLink: [
    {
      required: true,
      trigger: "blur",
      message: "请输入产品链接",
    },
  ],
});

const productName = (val: any) => {
  const arr = listCollect.value.productList.filter(
    (item: any) => item.productCode == val
  );
  if (arr && arr.length > 0) {
    addSupply.productName = arr[0].productName;
  }
};
const productTotal = (val: any) => {
  addSupply.productName = null
  addSupply.productCode = null


  const arr = listCollect.value.totalProduct.filter(
    (item: any) => item.productCategoryCode == val
  );
  // 看看 有没有数据 判断
  if (arr && arr.length > 0) {
    newProductList(arr[0].productCategoryCode);
    if (arr[0].productAttachmentList && arr[0].productAttachmentList[0]?.attachmentUri) {
      imgUpload1.value.newUrl(arr[0].productAttachmentList[0]?.attachmentUri, true)
    }
    addSupply.attachmentUri = arr[0].productAttachmentList[0]?.attachmentUri;
    addSupply.productCategory = arr[0].productCategory;
  }
};
const newProductList = async (item: string) => {
  newProductListOption.value = [];
  searchLoading.value = true
  const res = await getProductListAll({ productCategoryCode: item });
  console.log(res);

  if (res.code == 20000) {
    newProductListOption.value =
      res.data &&
      res.data.map((item: any) => {
        return {
          ...item,
          key: item.productCode,
          value: `${item.productCode} - ${item.productName}`,
          id: item.id,
          label: item.productName,
        };
      });
    searchLoading.value = false
  } else {
    searchLoading.value = false
  }
};
//显示弹框
const show = (type: string, row?: any) => {
  global.$resetForm(supplyFormRef.value, addSupply);
  if (type === "add") {
    dialogBasic.value.title = "新建产品链接配置";
  } else {
    newProductList(row.productCategoryCode);
    // 
    dialogBasic.value.title = "编辑产品链接配置";
    global.$objCopy(addSupply, row);
    // 图片显示
    nextTick(() => {
      if (row.attachmentUri) {
        imgUpload1.value.newUrl(row.attachmentUri, true)
      }
    })
  }
  dialogBasic.value.visible = true;

};
const onClose = () => {
  resetForm();
  searchLoading.value = false
  newProductListOption.value = [];
  dialogBasic.value.visible = false;
};
const resetForm = () => {
  supplyFormRef.value?.resetFields();
};
const onConfirm = async () => {
  await supplyFormRef.value?.validate(async (isOk) => {
    if (isOk) {
      try {
        const res = await productLinkConfigAddPost({ ...addSupply });
        if (res.code == 20000) {
          ElMessage({
            message: addSupply?.id
              ? "产品链接配置编辑成功"
              : "产品链接配置新增成功",
            type: "success",
          });
          if (addSupply.id) {
            emit("searchEdit");
          } else {
            emit("refresh");
          }
          onClose();
        }
      } catch (error) {
        ElMessage({
          message: addSupply?.id
            ? "产品链接配置编辑失败 请重试！"
            : "产品链接配置新增失败 请重试！",
          type: "warning",
        });
      }
    }
  });
};
const file1 = async (file: any) => {
  console.log(file);

  if (file.length) {
    const formData = new FormData()
    formData.append("file", file[0])
    formData.append("param", JSON.stringify({ module: "productCategory", type: "banner" }))
    upload(formData).then((res) => {
      let { data } = res;
      if (res.code == 20000) {
        addSupply.attachmentUri = data.attachmentUri
      }
    });

  } else {


  }
}
defineExpose({
  show,
});
</script>

<template>
  <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
    :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
    @on-close="onClose" @on-confirm="onConfirm">
    <template v-slot:content>
      <el-form ref="supplyFormRef" :model="addSupply" :rules="rules" label-width="100px" class="demo-ruleForm"
        status-icon>
        <el-form-item label="产品大类" prop="productCategoryCode">
          <BlackSelect v-model:select-value="addSupply.productCategoryCode" :filterable="true"
            :options="listCollect.totalProduct" @my-change="productTotal">
          </BlackSelect>
        </el-form-item>
        <el-form-item label="产品名称" prop="productCode">
          <BlackSelect v-loading="searchLoading" v-model:select-value="addSupply.productCode" :filterable="true"
            :options="newProductListOption" @my-change="productName">
          </BlackSelect>
        </el-form-item>

        <el-form-item label="产品链接" prop="productLink">
          <AddInput v-model:model-value="addSupply.productLink" maxlength="256" :limit="true"></AddInput>
        </el-form-item>

        <el-form-item label="环境" prop="environment">
          <BlackSelect v-model:select-value="addSupply.environment" :filterable="true" :options="listCollect.envList">
          </BlackSelect>
        </el-form-item>
        <el-form-item label="场景" prop="scenario">
          <BlackSelect v-model:select-value="addSupply.scenario" :filterable="true" :options="listCollect.sceneList">
          </BlackSelect>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <BlackSelect v-model:select-value="addSupply.status" :filterable="true"
            :options="ProductLinkConfigStatusEnum">
          </BlackSelect>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <AddInput v-model:model-value="addSupply.remarks" :limit="true" maxlength="128"></AddInput>
        </el-form-item>
        <!-- 图片 -->
        <el-form-item label="附件照片">
          <upLoadImgSingle ref="imgUpload1" @fileUp="file1"></upLoadImgSingle>
        </el-form-item>
      </el-form>
    </template>
  </SysDialog>
</template>

<style lang="scss" scoped>
.demo-ruleForm {
  max-height: 600px;
  overflow: auto;
}
</style>
